﻿using ConsultasGerais.GeocodeService;
using ConsultasGerais.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ConsultasGerais.Controllers
{
    public class ConsultasGeraisController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CEP()
        {
            return View();
        }

        public ActionResult FIPE()
        {
            return View();
        }

        public ActionResult PrevisaoTempo()
        {
            return View();
        }

        public ActionResult Cotacoes()
        {
            return View();
        }

        public ActionResult Megasena()
        {
            return View();
        }

        public ActionResult GetLocations(string endereco)
        {
            string lat = string.Empty;
            string lng = string.Empty;

            GeocodeRequest geocodeRequest = new GeocodeRequest();

            // Set the credentials using a valid Bing Maps key
            geocodeRequest.Credentials = new GeocodeService.Credentials();
            geocodeRequest.Credentials.ApplicationId = "AvW00CilYAUa8-GrAXIZl9dT6FL6-I73IOUxFk6xrsqUZ0T4vZZPdL787K02to-I";

            // Set the full address query
            geocodeRequest.Query = endereco;

            // Set the options to only return high confidence results 
            ConfidenceFilter[] filters = new ConfidenceFilter[1];
            filters[0] = new ConfidenceFilter();
            filters[0].MinimumConfidence = GeocodeService.Confidence.High;

            // Add the filters to the options
            GeocodeOptions geocodeOptions = new GeocodeOptions();
            geocodeOptions.Filters = filters;
            geocodeRequest.Options = geocodeOptions;
            ExecutionOptions execOptions = new ExecutionOptions();

            // Make the geocode request
            GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");

            if (geocodeService.Geocode(geocodeRequest).Results.Any(o => o.Locations != null && o.Locations.Any()))
            {
                lat = geocodeService.Geocode(geocodeRequest).Results.FirstOrDefault().Locations.FirstOrDefault().Latitude.ToString().Replace(',', '.');
                lng = geocodeService.Geocode(geocodeRequest).Results.FirstOrDefault().Locations.FirstOrDefault().Longitude.ToString().Replace(',', '.');
            }

            geocodeService.GeocodeAsync(geocodeRequest);

            var locations = new List<Locations>() {
                new Locations(lat, lng)
            };
            return Json(locations, JsonRequestBehavior.AllowGet);
        }

    }
}
